package com.itheima.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.PageResult;
import com.itheima.constant.QueryPageBean;
import com.itheima.dao.CheckGroupDao;
import com.itheima.pojo.CheckGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    public CheckGroupDao checkGroupDao;

    /**
     * 添加检查组
     * @param checkGroup
     * @param checkitemIds
     */
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
       checkGroupDao.add(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        setCheckGroupAndeCheckItem(checkitemIds, checkGroupId);
    }

    private void setCheckGroupAndeCheckItem(Integer[] checkitemIds, Integer checkGroupId) {
        if (checkitemIds!=null&&checkitemIds.length>0){
            Map<String,Integer> map=new HashMap<>();
            map.put("checkgroup_id",checkGroupId);
            for (Integer checkitemId : checkitemIds) {
                map.put("checkitem_id",checkitemId);
                checkGroupDao.setCheckGroupAndChevkItem(map);
            }
        }
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup>page=checkGroupDao.selectByString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据id查询
     * @param checkgroupId
     * @return
     */
    @Override
    public CheckGroup findById(Integer checkgroupId) {
        CheckGroup checkGroup=checkGroupDao.findById(checkgroupId);
        return checkGroup;
    }
    /**
     * 根据组合id查询对应检查项的id
     * @param checkgroupId
     * @return
     */
    @Override
    public List<Integer> findCheckitemIdsByCheckgroupId(Integer checkgroupId) {
        List<Integer> checkGroup=checkGroupDao.findCheckitemIdsByCheckgroupId(checkgroupId);
        return checkGroup;
    }

    /**
     * 编辑
     * @param checkGroup
     * @param checkitemIds
     */
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.deleteRelationship(checkGroup.getId());
        setCheckGroupAndeCheckItem(checkitemIds,checkGroup.getId());
        checkGroupDao.edit(checkGroup);
    }

    /**
     * 查询所有检查组
     * @return
     */
    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
}
